/**
 * Created by Forcs on 16/4/12.
 */

var express = require('express');
var request = require('request');
var Stbs = require('../models/Stbs');
var Config = require('../models/Config');
var TempLogs = require('../models/logs/TempLogs');
var Flavors = require('../models/Flavors');
var Products = require('../models/Products');
var VisitedEveryday = require('../models/VisitedEveryday');
var co = require('co');
var moment = require('moment');
var MapReduceBuilder = require('../db/MapReduceBuilder');
var ModelBuilder = require('../db/ModelBuilder');
var LogUtils = require("../utils/log/LogUtils.js");

var AppLogsResolver = require('../resolvers/AppLogsResolver');
var ContentLogsResolver = require('../resolvers/ContentLogsResolver');

var MainController = function () {};

MainController.prototype.onCreate = function () {
  var _self = this;
  var logRecycler = _self.$application.getService('LogRecycler');
  var configuration = _self.$application.getService('Configuration');
  logRecycler.options.intervalSecond = 30;
  logRecycler.options.logSources = [
    'http://127.0.0.1:28060/recycle'
  ];
  logRecycler.on('handle-task', function (item) {
    console.log('on request', item);
    return new Promise(function (resolve, reject) {
      co(function * () {
        var timestamps = {
          app: yield configuration.get('app', 0),
          content: yield configuration.get('content', 0)/*,
          page: yield configuration.get('page', 0),
          event: yield configuration.get('event', 0),
          order: yield configuration.get('order', 0)*/
        };
        request.post(
          item,
          {
            form: timestamps
          }, function (err, response, body) {
            if (err) {
              LogUtils.error(err.toString());
              reject(err);
              return;
            }
            resolve(JSON.parse(body));
          });
      }).catch(function (err) {
        LogUtils.error(err.toString());
        reject(err);
      });
      
    });
  });
  logRecycler.on('after-task', function (item, result) {
    return new Promise(function (resolve, reject) {
      co(function *() {
        var editor = configuration.editor();
        for (var key in result) {
          var logs = result[key].logs;
          var len = logs.length;
          for (var i = 0; i < len; i++) {
            var logItem = logs[i];
            var logContent = logItem.content;
            var user = yield Stbs.$manager.findUser(logContent.stbid, logContent.biz);
            if (!user) {
              yield Stbs.$manager.insert({
                stbId: logContent.stbid,
                biz: logContent.biz,
                createAt: moment(logItem.timestamp, 'X').format('YYYY-MM-DD HH:mm:ss'),
                createAtTimestamp: logItem.timestamp
              });
              logItem.content.isNewUser = true;
            } else {
              var createDate = user.createAt.split(' ')[0];
              logItem.content.isNewUser = createDate === logItem.date;
            }
          }
          var length = logs.length;
          if (length > 0) {
            var slicing = 10000;
            if (length > slicing) {
              var tail = length % slicing;
              var n = parseInt(length / slicing);
              for (var s = 0; s < n; s++) {
                yield TempLogs.$manager.saveLogs(logs.slice(s * slicing, s * slicing + slicing));
              }
              if (tail) {
                yield TempLogs.$manager.saveLogs(logs.slice(n * slicing, n * slicing + tail));
              }
            } else {
              yield TempLogs.$manager.saveLogs(logs);
            }
            if (key === 'app') {
              yield new AppLogsResolver().resolve();
            } else if (key === 'content') {
              yield new ContentLogsResolver().resolve();
            }
            editor.put(key, result[key].lastTimestamp);
          } else {
            editor.put(key, yield configuration.get(key, 0));
          }
          LogUtils.info('load logs ' + key + ' completion length ' + length);
        }
        yield editor.commit();
        yield TempLogs.$manager.mergeToAppLogs();
        LogUtils.info('load logs completion');
        resolve(true);
      }).catch(function (err) {
        LogUtils.error(err.toString());
        reject(err);
      });
    });
  });
  _self.$logRecycler = logRecycler;
};

MainController.prototype.onStart = function () {
  var _self = this;
  _self.$logRecycler.start();
};

module.exports = MainController;